package pre.bookcloud.java21.qoder.historysign02;

import java.awt.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import javax.swing.*;

/** Statistics UI Interface 统计分析UI界面 */
public class StatisticsUI extends JPanel {

  private JLabel titleLabel;
  private JPanel statisticsPanel;
  private JPanel chartPanel;

  public StatisticsUI() {
    initializeComponents();
    setupLayout();
    loadStatistics();
  }

  /** Initialize UI components 初始化UI组件 */
  private void initializeComponents() {
    setLayout(new BorderLayout());
    setBackground(Color.WHITE);

    // Title label
    titleLabel = new JLabel("签到统计分析", JLabel.CENTER);
    titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 20));
    titleLabel.setForeground(new Color(51, 102, 255));

    // Statistics panel
    statisticsPanel = new JPanel();
    statisticsPanel.setLayout(new BoxLayout(statisticsPanel, BoxLayout.Y_AXIS));
    statisticsPanel.setBackground(Color.WHITE);
    statisticsPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

    // Chart panel (placeholder for future chart implementation)
    chartPanel = new JPanel();
    chartPanel.setBackground(new Color(245, 245, 245));
    chartPanel.setBorder(BorderFactory.createTitledBorder("签到趋势图"));
    chartPanel.setPreferredSize(new Dimension(0, 200));

    // Add placeholder text for chart
    JLabel chartPlaceholder = new JLabel("图表功能开发中...", JLabel.CENTER);
    chartPlaceholder.setFont(new Font("微软雅黑", Font.ITALIC, 14));
    chartPlaceholder.setForeground(Color.GRAY);
    chartPanel.setLayout(new BorderLayout());
    chartPanel.add(chartPlaceholder, BorderLayout.CENTER);
  }

  /** Setup the layout 设置布局 */
  private void setupLayout() {
    // Top panel with title
    JPanel topPanel = new JPanel(new BorderLayout());
    topPanel.setBackground(Color.WHITE);
    topPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
    topPanel.add(titleLabel, BorderLayout.CENTER);

    // Main content panel
    JPanel contentPanel = new JPanel(new BorderLayout(0, 20));
    contentPanel.setBackground(Color.WHITE);
    contentPanel.add(statisticsPanel, BorderLayout.CENTER);
    contentPanel.add(chartPanel, BorderLayout.SOUTH);

    // Add to main panel
    add(topPanel, BorderLayout.NORTH);
    add(contentPanel, BorderLayout.CENTER);
  }

  /** Load and display statistics 加载并显示统计数据 */
  private void loadStatistics() {
    statisticsPanel.removeAll();

    // Get current data
    List<Student> todayStudents = DataUtil.getTodaySignData();
    List<Student> historyStudents = DataUtil.getHistoryList();

    // Calculate today's statistics
    int todayTotal = todayStudents.size();
    int todaySigned = (int) todayStudents.stream().filter(s -> s.getStatus() == 1).count();
    int todayUnsigned = todayTotal - todaySigned;
    double todayRate = todayTotal > 0 ? (double) todaySigned / todayTotal * 100 : 0;

    // Calculate history statistics
    int historyTotal = historyStudents.size();

    // Create statistics cards
    addStatisticCard(
        "今日签到统计",
        String.format("总人数: %d人", todayTotal),
        String.format("已签到: %d人", todaySigned),
        String.format("未签到: %d人", todayUnsigned),
        String.format("签到率: %.1f%%", todayRate),
        new Color(144, 238, 144));

    addStatisticCard(
        "历史记录统计",
        String.format("累计签到记录: %d次", historyTotal),
        String.format(
            "当前日期: %s", LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"))),
        "活跃学生: " + getActiveStudentsCount() + "人",
        "系统运行: 正常",
        new Color(173, 216, 230));

    addStatisticCard(
        "系统信息",
        "应用版本: 1.0.0",
        "数据更新: 实时",
        "在线用户: 1人",
        "最后刷新: " + java.time.LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")),
        new Color(255, 218, 185));

    statisticsPanel.revalidate();
    statisticsPanel.repaint();
  }

  /** Add a statistics card to the panel 添加统计卡片到面板 */
  private void addStatisticCard(
      String title, String info1, String info2, String info3, String info4, Color backgroundColor) {
    JPanel card = new JPanel();
    card.setLayout(new BoxLayout(card, BoxLayout.Y_AXIS));
    card.setBackground(backgroundColor);
    card.setBorder(
        BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(backgroundColor.darker(), 1),
            BorderFactory.createEmptyBorder(15, 20, 15, 20)));
    card.setMaximumSize(new Dimension(Integer.MAX_VALUE, 120));

    // Title
    JLabel titleLabel = new JLabel(title);
    titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
    titleLabel.setForeground(new Color(51, 51, 51));
    titleLabel.setAlignmentX(Component.LEFT_ALIGNMENT);

    // Information labels
    JLabel info1Label = createInfoLabel(info1);
    JLabel info2Label = createInfoLabel(info2);
    JLabel info3Label = createInfoLabel(info3);
    JLabel info4Label = createInfoLabel(info4);

    card.add(titleLabel);
    card.add(Box.createVerticalStrut(5));
    card.add(info1Label);
    card.add(info2Label);
    card.add(info3Label);
    card.add(info4Label);

    statisticsPanel.add(card);
    statisticsPanel.add(Box.createVerticalStrut(10));
  }

  /** Create an information label 创建信息标签 */
  private JLabel createInfoLabel(String text) {
    JLabel label = new JLabel(text);
    label.setFont(new Font("微软雅黑", Font.PLAIN, 12));
    label.setForeground(new Color(66, 66, 66));
    label.setAlignmentX(Component.LEFT_ALIGNMENT);
    return label;
  }

  /**
   * Get count of active students (students who have signed in at least once) 获取活跃学生数量（至少签到过一次的学生）
   */
  private int getActiveStudentsCount() {
    return (int) DataUtil.getTodaySignData().stream().filter(s -> s.getStatus() == 1).count();
  }

  /** Refresh statistics data 刷新统计数据 */
  public void refreshStatistics() {
    loadStatistics();
  }
}
